//
//  WFOAuthVC.swift
//  WangFangWeiBo
//
//  Created by 王方 on 16/7/10.
//  Copyright © 2016年 wf. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

//微博appkey
let WeiBoAppKey = "1549202722"
//微博appsecrect
let WeiBoAppSecret = "b4cbd67e1fe081dc9a4e6a79f999bb69"
//微博授权回调页
let WeiBoRedirect_Uri = "http://www.gamersky.com/"

class WFOAuthVC: UIViewController {

    // MARK:  - 懒加载控件
    private lazy var webView:UIWebView = UIWebView()
    
    //重写loadview方法替换视图
    override func loadView() {
        
        webView.delegate = self
        webView.opaque = false
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.whiteColor()
        setUpUI()
        requestOAuthLogin()
    }
    
    // MARK:  - 加载网页
    private func requestOAuthLogin(){
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(WeiBoAppKey)&redirect_uri=\(WeiBoRedirect_Uri)"
        let request = NSURLRequest(URL: NSURL(string: url)!)
        webView.loadRequest(request)
    }
    
    // MARK:  - 初始化导航栏
    func setUpUI(){
        navigationItem.title = "微博登录"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: "cancel")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: "autoFillUsernameAndPWD")
    }
    
    // MARK:  - 取消按钮
    @objc private func cancel(){
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    // MARK:  - 自动填充
    @objc private func autoFillUsernameAndPWD(){
        print("执行自动填充")
        webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = '576398927@qq.com'; document.getElementById('passwd').value = 'wf871111'")
    }
   
    // MARK:  - 请求授权码
//    func requestAccessToken(code:String){
//        let urlStr = "https://api.weibo.com/oauth2/access_token"
//        let dic = [
//            "client_id":WeiBoAppKey,
//            "client_secret":WeiBoAppSecret,
//            "grant_type":"authorization_code",
//            "code":code,
//            "redirect_uri":WeiBoRedirect_Uri
//        ]
//        
//        let ma = AFHTTPSessionManager()
//        ma.responseSerializer.acceptableContentTypes?.insert("text/plain")
//        
//        ma.POST(urlStr, parameters: dic, progress: nil, success: { (_, response) -> Void in
//            guard let dic = response else {
//                print("不是一个正常的dic")
//                return
//            }
//            //到这里为止,dic返回是正确的
//          let userAccount = WFUserAccount(dic:dic as! [String : AnyObject])
//            print(userAccount)
//            
//            }, failure: { (_, error) -> Void in
//                print(error)
//        })
//        WFNetWorkTools.sharedTools.requsetAccessToken(code) { (response, error) -> () in
//            if error != nil {
//            //说明网络请求有误
//                print(error)
//            }else{
//                //说明网络请求成功
//                guard let dic = response else {
//                    print("不是一个正常的dic")
//                    return
//                }
//                                //到这里为止,dic返回是正确的
//                let userAccount = WFUserAccount(dic:dic as! [String : AnyObject])
//                
//                print(userAccount)
//                // MARK:  - 网络请求获取用户信息
//                self.requestUserInfo(userAccount)
//            }
//        }
        
        
//    }

//    func requestUserInfo(userInso:WFUserAccount){
//        WFNetWorkTools.sharedTools.requestUserInfo(userInso) { (response, error) -> () in
//            if error != nil {
//                //说明网络请求有误
//                print(error)
//            }else{
//                //说明网络请求成功
//                guard let dic = response else {
//                    print("不是一个正常的dic")
//                    return
//                }
//                //到这里为止,dic返回是正确的
//                //获取名字
//                let name = dic["name"]
//                //获取头像
//                let avatar_large = dic["avatar_large"]
//                
//                //设置给userInso
//                userInso.name = name as? String
//                userInso.avatar_large = avatar_large as? String
//                print(userInso)
//                //保存到沙盒中
//                userInso.saveUserAccount()
//            }
//        }
//    }
    

}

 // MARK:  - 定义延展
extension WFOAuthVC:UIWebViewDelegate {
    //将要加载的时候
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let url = request.URL else {
            return false
        }
        //到这里为止,url就是有值的
        
        if !url.absoluteString.hasPrefix(WeiBoRedirect_Uri){
            return true
        }
        
        //到这里为止,就是我们需要处理的请求了
        
        if let query = url.query where query.hasPrefix("code="){
            //我们就截取code
            let code = query.substringFromIndex("code=".endIndex)
            print("千辛万苦获得的code:\(code)")
            
//            requestAccessToken(code)
            WFUserAccountViewModel.sharedUserAccount.requestAccessToken(code, callBack: { (isSuccess) -> () in
                if isSuccess{
                print("登录成功")
                    //发送通知进行跳转
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        //为了区分,把self传过去
                        NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootVCNotification, object: self)
                    })
                }else{
                print("登录失败")
                }
            })
            
        }else{
            //说明点击了取消授权按钮
            dismissViewControllerAnimated(true, completion: nil)
        }
        
        
        return false
    }
    //开始加载的时候
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    //加载完毕的时候执行
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //加载失败的时候执行
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }
    
    
}